from random import Random

from django.core.mail import send_mail

from mx.settings import EMAIL_FROM, DOMAIN_NAME
from apps.users.models import EmailVerifyRecord


def randomStr(randomLength=8):
    """
    从code字符串中随机生产8个长度的字符串
    """
    str = ""
    code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    length = len(code)-1
    random = Random()
    for i in range(randomLength):
        str += code[random.randint(0,length)]
    return str

def send(email,sendType):
    """
    发送邮件
    """
    code = randomStr(16)
    emailRecode = EmailVerifyRecord()
    emailRecode.code = code
    emailRecode.email = email
    emailRecode.sendType = sendType

    # 注册
    if sendType == "register":
        title = "在线学习注册激活链接"
        message = "点击下面的链接激活账号: {0}/users/active/{1}".format(DOMAIN_NAME, code)
        send_state = send_mail(title, message, EMAIL_FROM, [email])
        # 邮件发送成功后再保存邮件信息
        if send_state:
            emailRecode.save()
    # 通过邮箱重置密码
    elif sendType == "forget":
        title = "密码重置链接"
        message = "请点击下面的链接重置密码: {0}/users/passwordReset/{1}".format(DOMAIN_NAME,code)
        state = send_mail(title, message, EMAIL_FROM, [email])
        if state:
            emailRecode.save()
    # 修改邮箱
    elif sendType == "modifyEmail":
        title = "修改邮箱验证码"
        message = "验证码为: {0}".format(code)
        state = send_mail(title, message, EMAIL_FROM, [email])
        if state:
            emailRecode.save()



